import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../../widgets/task_list_item.dart';
import '../../services/api_service.dart';
import '../../services/auth_service.dart';
import '../../utils/message_box.dart';
import '../../utils/utils.dart';
import '../../utils/rangeInput_formatter.dart';
import '../system/fontsize_provider.dart';

class PickingScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  const PickingScreen({super.key, required this.jsonData});

  @override
  _PickingScreenState createState() => _PickingScreenState();
}

class _PickingScreenState extends State<PickingScreen> with WidgetsBindingObserver {
  final _itemNumberController = TextEditingController();
  final _locationController = TextEditingController();
  final _lPNBINController = TextEditingController();
  final _qtyController = TextEditingController();
  
  // 【关键修复1：复制MoveStock焦点控制器配置，添加canRequestFocus: true】
  final FocusNode _itemNumberFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _locationFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _lPNFocusNode = FocusNode(canRequestFocus: true);
  final FocusNode _quantityFocusNode = FocusNode(canRequestFocus: true);
  
  // 键盘状态管理（新增_currentFocusField，与MoveStock一致）
  bool _itemKeyboardVisible = false;
  bool _locationKeyboardVisible = false;
  bool _lpnKeyboardVisible = false;
  bool _quantityKeyboardVisible = false;
  String? _currentFocusField;

  Map<String, dynamic>? taskData = null;
  bool isLoading = true;

  late int waveId;
  late int taskId;
  late int remainTask = 0;
  int? warehouseId;
  String? packType;
  String? packKey;
  String? itemNumber;
  String? location;
  int maxAllowedValue = 0;

  late double _fontScale;
  String? sourceScreen;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    
    // 【关键修复2：复制MoveStock焦点监听逻辑】
    _initFocusListeners();
    
    // 原有业务参数初始化
    waveId = widget.jsonData['waveId'];
    sourceScreen = widget.jsonData['source'];
    print('PickingScreen 从 ${sourceScreen ?? "未知页面"} 跳转而来');
    
    _getWarehouseId().then((_) {
      if (warehouseId != null) {
        _callGetPickTaskAPI();
      } else {
        MessageBox.showMessageBox(context, 'Missing warehouse Id.', isError: true);
        setState(() => isLoading = false);
      }
    });
    print('waveId-----${waveId}');
    
    // 【关键修复3：完全复制MoveStock初始化聚焦逻辑】先隐藏键盘再聚焦
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (mounted) {
        await _hideKeyboard(); // 确保键盘先收起
        _focusOnField('item', showKeyboard: false); // 聚焦不弹键盘
      }
    });
  }

  // 【关键修复4：完全复制MoveStock焦点监听方法】
  void _initFocusListeners() {
    // Quantity保留原有业务逻辑：获得焦点自动弹键盘
    _quantityFocusNode.addListener(() {
      _handleFocusChange('quantity', _quantityFocusNode);
      if (_quantityFocusNode.hasFocus && !_quantityKeyboardVisible) {
        _showKeyboardForField('quantity');
      }
    });
    
    // 其他输入框：获得焦点时强制隐藏键盘（与MoveStock一致）
    _itemNumberFocusNode.addListener(() {
      _handleFocusChange('item', _itemNumberFocusNode);
      if (_itemNumberFocusNode.hasFocus && !_itemKeyboardVisible) {
        _hideKeyboard();
      }
    });
    
    _locationFocusNode.addListener(() {
      _handleFocusChange('location', _locationFocusNode);
      if (_locationFocusNode.hasFocus && !_locationKeyboardVisible) {
        _hideKeyboard();
      }
    });
    
    _lPNFocusNode.addListener(() {
      _handleFocusChange('lpn', _lPNFocusNode);
      if (_lPNFocusNode.hasFocus && !_lpnKeyboardVisible) {
        _hideKeyboard();
      }
    });
  }

  // 【关键修复5：完全复制MoveStock焦点变化处理】
  void _handleFocusChange(String field, FocusNode node) {
    if (node.hasFocus) {
      // 切换焦点时先隐藏上一个输入框的键盘
      if (_currentFocusField != null && _currentFocusField != field) {
        _hideKeyboardForField(_currentFocusField!);
      }
      _setCurrentFocusField(field);
    } else if (_currentFocusField == field) {
      // 失去焦点时隐藏当前键盘并重置状态
      _hideKeyboardForField(field);
      _currentFocusField = null;
    }
  }

  // 应用生命周期监听（与MoveStock一致）
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed && mounted) {
      _resetAllKeyboards();
    }
  }

  // 【关键修复6：完全复制MoveStock键盘控制方法】
  void _setCurrentFocusField(String field) => setState(() => _currentFocusField = field);
  
  void _showKeyboard() async => await SystemChannels.textInput.invokeMethod('TextInput.show');
  
  // 两次隐藏+延迟+异常重试，确保键盘彻底收起（MoveStock核心）
  Future<void> _hideKeyboard() async {
    try {
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
      await Future.delayed(const Duration(milliseconds: 50));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    } catch (e) {
      print('隐藏键盘失败: $e');
      await Future.delayed(const Duration(milliseconds: 100));
      await SystemChannels.textInput.invokeMethod('TextInput.hide');
    }
  }
  
  // 先更新状态再显示键盘（避免状态滞后）
  void _showKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, true);
    _showKeyboard();
  });
  
  // 先更新状态再隐藏键盘（与MoveStock一致）
  void _hideKeyboardForField(String field) => setState(() {
    _updateKeyboardState(field, false);
    _hideKeyboard();
  });
  
  // 【关键修复7：复制MoveStock切换键盘逻辑】
  void _toggleKeyboardForField(String field) {
    if (_getKeyboardState(field)) {
      _hideKeyboardForField(field);
      _unfocusField(field);
    } else {
      _focusOnField(field, showKeyboard: true);
    }
  }
  
  // 【关键修复8：复制MoveStock聚焦方法（核心）】带showKeyboard参数控制
  void _focusOnField(String field, {required bool showKeyboard}) {
    FocusScope.of(context).unfocus(); // 先取消所有焦点，避免冲突
    if (mounted) {
      // 聚焦目标输入框
      switch (field) {
        case 'item':
          FocusScope.of(context).requestFocus(_itemNumberFocusNode);
          break;
        case 'location':
          FocusScope.of(context).requestFocus(_locationFocusNode);
          break;
        case 'lpn':
          FocusScope.of(context).requestFocus(_lPNFocusNode);
          break;
        case 'quantity':
          FocusScope.of(context).requestFocus(_quantityFocusNode);
          break;
      }
      
      // 明确控制键盘显示/隐藏，同步状态
      if (showKeyboard) {
        _showKeyboardForField(field);
      } else {
        _hideKeyboard();
        _updateKeyboardState(field, false); // 强制同步状态为隐藏
      }
    }
  }
  
  // 【关键修复9：复制MoveStock取消焦点方法】
  void _unfocusField(String field) {
    switch (field) {
      case 'item': _itemNumberFocusNode.unfocus(); break;
      case 'location': _locationFocusNode.unfocus(); break;
      case 'lpn': _lPNFocusNode.unfocus(); break;
      case 'quantity': _quantityFocusNode.unfocus(); break;
    }
  }
  
  // 获取键盘状态（与MoveStock一致）
  bool _getKeyboardState(String field) {
    switch (field) {
      case 'item': return _itemKeyboardVisible;
      case 'location': return _locationKeyboardVisible;
      case 'lpn': return _lpnKeyboardVisible;
      case 'quantity': return _quantityKeyboardVisible;
      default: return false;
    }
  }
  
  // 更新键盘状态（与MoveStock一致）
  void _updateKeyboardState(String field, bool visible) {
    setState(() {
      switch (field) {
        case 'item': _itemKeyboardVisible = visible; break;
        case 'location': _locationKeyboardVisible = visible; break;
        case 'lpn': _lpnKeyboardVisible = visible; break;
        case 'quantity': _quantityKeyboardVisible = visible; break;
      }
    });
  }
  
  // 【关键修复10：复制MoveStock重置所有键盘状态】
  void _resetAllKeyboards() {
    if (_currentFocusField == null && !_itemKeyboardVisible && 
        !_locationKeyboardVisible && !_lpnKeyboardVisible && !_quantityKeyboardVisible) {
      return;
    }
    setState(() {
      _itemKeyboardVisible = false;
      _locationKeyboardVisible = false;
      _lpnKeyboardVisible = false;
      _quantityKeyboardVisible = false;
      _currentFocusField = null;
    });
    FocusScope.of(context).unfocus();
    _hideKeyboard();
  }

  // 【关键修复11：复制MoveStock输入框点击处理】仅聚焦不弹键盘
  void _onInputTap(TextEditingController controller, String fieldType) {
    if (controller.text.isNotEmpty) {
      // 保留原有选中文本逻辑
      controller.selection = TextSelection(
        baseOffset: 0,
        extentOffset: controller.text.length,
      );
    }
    
    // Quantity保留原有业务逻辑：点击显示键盘
    if (fieldType == 'quantity') {
      _focusOnField(fieldType, showKeyboard: true);
    } else {
      // 其他输入框：点击仅聚焦不弹键盘（与MoveStock一致）
      _focusOnField(fieldType, showKeyboard: false);
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    
    // 【关键修复12：复制MoveStock焦点监听移除逻辑】
    _itemNumberFocusNode.removeListener(() => _handleFocusChange('item', _itemNumberFocusNode));
    _locationFocusNode.removeListener(() => _handleFocusChange('location', _locationFocusNode));
    _lPNFocusNode.removeListener(() => _handleFocusChange('lpn', _lPNFocusNode));
    _quantityFocusNode.removeListener(() => _handleFocusChange('quantity', _quantityFocusNode));
    
    // 原有销毁逻辑
    _itemNumberFocusNode.dispose();
    _locationFocusNode.dispose();
    _lPNFocusNode.dispose();
    _quantityFocusNode.dispose();
    _itemNumberController.dispose();
    _locationController.dispose();
    _lPNBINController.dispose();
    _qtyController.dispose();
    
    super.dispose();
  }

  Future<void> _getWarehouseId() async {
    final user = Provider.of<AuthService>(context, listen: false).currentUser;
    if (user?.warehouse != null) {
      setState(() {
        warehouseId = user?.warehouse;
      });
    }
  }

  // 处理Item Number扫描输入（优化焦点跳转逻辑）
  void _handleItemNumberScanInput(String value) async {
    print('进来了---');
    try {
      if(value.contains(':')){
        itemNumber = Utils.parseQRCode(value, 'item number');
        packKey = Utils.parseQRCode(value, 'pack key');
        packType = packKey!.contains('Case')?'Case':'Each';
        setState(() {
          _itemNumberController.text = itemNumber ?? '';
        });
      }
      
      // 【关键修复13：用MoveStock风格的聚焦方法，确保不弹键盘】
      _focusOnField('location', showKeyboard: false);
    } catch (e) {
      setState(() {
        _itemNumberController.text = value;
        _itemNumberController.selection = TextSelection(
          baseOffset: 0,
          extentOffset: value.length,
        );
      });
      MessageBox.showMessageBox(context, e, isError: true);
    }
  }

  // 【保持原有样式不变】仅调整内部调用逻辑
  Widget _buildKeyboardInput({
    required String fieldType,
    required TextEditingController controller,
    required FocusNode focusNode,
    TextInputType keyboardType = TextInputType.text,
    List<TextInputFormatter>? inputFormatters,
    Function(String)? onSubmitted,
    bool isSmallScreen = false,
  }) {
    return SizedBox(
      height: 30,
      child: TextField(
        focusNode: focusNode,
        controller: controller,
        keyboardType: keyboardType,
        inputFormatters: inputFormatters,
        decoration: InputDecoration(
          border: const OutlineInputBorder(),
          contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 0),
          // 键盘图标后缀 - 保持原有样式
          suffixIcon: IconButton(
            icon: Icon(
              _getKeyboardState(fieldType) ? Icons.keyboard_hide : Icons.keyboard,
              color: const Color(0xFF008363),
              size: isSmallScreen ? 18 : 20,
            ),
            onPressed: () => _toggleKeyboardForField(fieldType),
            splashRadius: 16,
            padding: const EdgeInsets.all(2),
            constraints: const BoxConstraints.tightFor(width: 32, height: 32),
          ),
        ),
        style: TextStyle(fontSize: 12 * _fontScale),
        onChanged: (_) {},
        onSubmitted: onSubmitted,
        // 【关键修复14：调用新的点击处理方法】
        onTap: () => _onInputTap(controller, fieldType),
        // 【关键修复15：复制MoveStock外部点击逻辑】
        onTapOutside: (event) {
          _hideKeyboardForField(fieldType);
          _unfocusField(fieldType);
        },
      ),
    );
  }

  // 原有业务方法：获取任务数据（无修改）
  Future<void> _callGetPickTaskAPI() async {
    if (warehouseId == null) {
      MessageBox.showMessageBox(context, 'Warehouse ID is missing', isError: true);
      setState(() => isLoading = false);
      return;
    }

    final apiUrl = '${ApiService.baseURL}${ApiService.getpickTask}$waveId';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null || accessToken.isEmpty) {
      MessageBox.showMessageBox(context, 'Authentication failed', isError: true);
      setState(() => isLoading = false);
      return;
    }

    try {
      print('getpickTask url--$apiUrl');
      print('Using warehouseId: $warehouseId');

      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
        print('jsondata----$jsonData');
        if (jsonData['code'] == 2000) {
          setState(() {
            taskData = jsonData['data'];
            isLoading = false;
            maxAllowedValue = jsonData['data']?['required_quantity']??0;
            taskId = jsonData['data']?['id']??0;
            remainTask = jsonData['data']?['remaining_tasks']??0;
          });
          if(jsonData['data'].isEmpty){
            MessageBox.showMessageBox(context, jsonData['msg']);
          }
        } else {
          MessageBox.showMessageBox(context, jsonData['msg'], isError: true);
          setState(() => isLoading = false);
        }
      } else if (response.statusCode == 401) {
        AuthService().logout(context);
        MessageBox.showMessageBox(context, 'Session expired, please log in again.', isError: true);
        setState(() => isLoading = false);
      } else {
        MessageBox.showMessageBox(context, 'Server error: ${response.statusCode}', isError: true);
        setState(() => isLoading = false);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
      setState(() => isLoading = false);
    }
  }

  // 原有业务方法：执行拣货任务（无修改）
  Future<Map<String, dynamic>?> executePickTask() async {
    if (warehouseId == null) {
      throw('Warehouse ID is missing');
    }
    final apiUrl = '${ApiService.baseURL}${ApiService.executePickTask}';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null || accessToken.isEmpty) {
      MessageBox.showMessageBox(context, 'Authentication failed', isError: true);
      return null;
    }

    try {
      print('executePickTask url--$apiUrl');
      print('Using warehouseId: $warehouseId, waveId: $waveId');
      final requestBody = {
        'id': taskId,
        'picked_quantity': int.parse(_qtyController.text.trim()),
        'location':_locationController.text.trim().isEmpty?null:_locationController.text.trim(),
        'item_number':_itemNumberController.text.trim().isEmpty?null:_itemNumberController.text.trim(),
        'lpn_number':_lPNBINController.text.trim().isEmpty?null:_lPNBINController.text.trim()
      };
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );

      print('requestBody---$requestBody');
      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
        print('jsonData---$jsonData');
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else {
          throw(jsonData['msg']);
        }
      } else if (response.statusCode == 401) {
        AuthService().logout(context);
        throw('Session expired, please log in again.');
      } else {
        throw('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw(e.toString());
    }
  }

  // 加载下一个任务（仅优化焦点跳转逻辑）
  Future<void> loadNextTask() async{
    try{
      _resetAllKeyboards(); // 【关键修复16：用MoveStock的重置方法】
      
      if(_itemNumberController.text.isEmpty){
        MessageBox.showMessageBox(context, 'Item Number can`t be null.',isError: true);
        _focusOnField('item', showKeyboard: false); // 聚焦不弹键盘
        return;
      }
      else if(_itemNumberController.text != taskData!['item_number']){
        MessageBox.showMessageBox(context, 'Please enter the correct Item Number.',isError: true);
        _focusOnField('item', showKeyboard: false);
        return;
      }

      if(_locationController.text.isEmpty){
        MessageBox.showMessageBox(context, 'Location can`t be null.',isError: true);
        _focusOnField('location', showKeyboard: false);
        return;
      }
      else if(_locationController.text != taskData!['location']){
        // 显示带关闭按钮的提示对话框
        var dialogResult = await showDialog(
          context: context,
          barrierDismissible: false, // 不允许点击外部关闭
          builder: (BuildContext context) {
            return AlertDialog(
              // 使用contentPadding控制内边距，为右上角按钮留出空间
              contentPadding: const EdgeInsets.only(left: 20,right: 15,top: 10,bottom: 0),
              // 通过Stack实现右上角关闭按钮
              title: Stack(
                children: [
                  Text(
                    'Warning',
                    style: TextStyle(
                      fontSize: 18 * _fontScale, 
                      color: const Color.fromARGB(255, 240, 98, 2),
                      fontWeight: FontWeight.bold
                    ),
                  ),
                  // 右上角关闭按钮
                  Positioned(
                    top: -15,
                    right: 0,
                    child: IconButton(
                      icon: Icon(
                        Icons.close,
                        color: Colors.grey[500],
                        size: 20 * _fontScale,
                      ),
                      onPressed: () {
                        // 仅关闭弹窗，不跳转
                        Navigator.of(context).pop();
                      },
                      padding:EdgeInsets.all(0),
                      splashRadius: 20, // 减小点击反馈范围
                    ),
                  ),
                ],
              ),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text(
                      'Location ${_locationController.text} does not match, a count task will be generated. Do you want to continue?',
                      style: TextStyle(fontSize: 16 * _fontScale),
                    ),
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: Text(
                    'Cancel',
                    style: TextStyle(
                      fontSize: 16 * _fontScale,
                      color: Colors.black87
                    ),
                  ),
                  onPressed: () {
                    Navigator.of(context).pop(false);
                    return;
                  },
                ),
                TextButton(
                  child: Text(
                    'Continue',
                    style: TextStyle(
                      fontSize: 16 * _fontScale,
                      color: const Color(0xFF008363)
                    ),
                  ),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                ),
              ],
            );
          },
        );
        print('dialogResult======$dialogResult');
        // 关键判断：根据对话框返回值决定是否继续
        if (dialogResult != true) { 
          // 点击“取消”或关闭图标：返回false/null，直接阻断后续代码
          _focusOnField('location', showKeyboard: false);
          return; // 核心：直接return，不再执行下面的数量校验、接口调用等逻辑
        }
      }

      if(_qtyController.text.isEmpty){
        MessageBox.showMessageBox(context, 'Quantity can`t be null.',isError: true);
        _focusOnField('quantity', showKeyboard: true); // 保留Quantity弹键盘逻辑
        return;
      }
      else if(_qtyController.text != taskData!['required_quantity'].toString()){
        MessageBox.showMessageBox(context, 'Please enter the correct quantity.',isError: true);
        _focusOnField('quantity', showKeyboard: true);
        return;
      }

      if(_lPNBINController.text.isNotEmpty && _lPNBINController.text.trim() != taskData!['lpn_number'].toString()){
        if(taskData!['lpn_number'] == null){
          MessageBox.showMessageBox(context, 'Invaild LPN number, no LPN number for this item.',isError: true);
        }else{
          MessageBox.showMessageBox(context, 'Please enter the correct LPN number.',isError: true);
        }
        _focusOnField('lpn', showKeyboard: false);
        return;
      }

      final jsonData = await executePickTask();
      if(jsonData != null && jsonData['code'] == 2000){
        setState(() => _clearInputFields());
        await _callGetPickTaskAPI(); 
        
        if(remainTask > 0){
          MessageBox.showMessageBox(context, jsonData['msg']);
          if (mounted) _focusOnField('item', showKeyboard: false);
        }else if(remainTask == 0){
          Navigator.pushNamed(
            context,
            '/picking/picking-details',
            arguments: {'waveId': waveId, 'source': sourceScreen}
          ).then((result) {
            if (result == true) {
              setState(() => _clearInputFields());
              _callGetPickTaskAPI();
              if (mounted) _focusOnField('item', showKeyboard: false);
            }
          });
        }
      }
    }catch(e){
      MessageBox.showMessageBox(context, e,isError: true);
    }
  }

  void _clearInputFields() {
    _itemNumberController.clear();
    _locationController.clear();
    _lPNBINController.clear();
    _qtyController.clear();
  }

  // 【完全保持原有页面样式】无任何UI修改
  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final isSmallScreen = MediaQuery.of(context).size.width < 360;

    if (isLoading) {
      return Scaffold(
        appBar: AppBar(
          title: Text('Picking', style: TextStyle(fontSize: 18 * _fontScale)),
          leading: IconButton(
            icon: const Icon(Icons.arrow_back, color: Colors.white),
            onPressed: sourceScreen == 'singlePicking' ?
                    () {
                      _resetAllKeyboards(); // 用新的重置方法
                      Navigator.pushNamed(
                        context,
                        '/outbound/single-picking',
                        arguments: {'waveId': waveId}
                      );
                    }
                    :
                    () {
                      _resetAllKeyboards();
                      Navigator.pushNamed(
                        context,
                        '/outbound/bin-assignment',
                        arguments: {'waveId': waveId}
                      );
                    },
          ),
          actions: [
            IconButton(
              icon: const Icon(Icons.home, color: Colors.white),
              onPressed: () {
                _resetAllKeyboards();
                Navigator.pushNamed(context, '/home');
              },
            ),
          ],
          backgroundColor: const Color(0xFF008363),
        ),
        body: const Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('Picking', style: TextStyle(fontSize: 18 * _fontScale)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: sourceScreen == 'singlePicking' ?
                  () {
                    _resetAllKeyboards();
                    Navigator.pushNamed(
                      context,
                      '/outbound/single-picking',
                      arguments: {'waveId': waveId}
                    );
                  }
                  :
                  () {
                    _resetAllKeyboards();
                    Navigator.pushNamed(
                      context,
                      '/outbound/bin-assignment',
                      arguments: {'waveId': waveId}
                    );
                  },
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () {
              _resetAllKeyboards();
              Navigator.pushNamed(context, '/home');
            },
          ),
        ],
        backgroundColor: const Color(0xFF008363),
      ),
      resizeToAvoidBottomInset: false,
      body: GestureDetector(
        onTap: _resetAllKeyboards, // 【关键修复17：用MoveStock的重置方法】
        behavior: HitTestBehavior.opaque,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.only(left: 32,right: 32,top: 5,bottom: 64),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    TaskListItem(
                      icon: Icons.list_alt,
                      label: 'Order:',
                      value: taskData?['order_number'] ?? 'N/A',
                    ),
                    TaskListItem(
                      icon: Icons.waves,
                      label: 'Wave:',
                      value: taskData?['pickwave_name'] ?? 'N/A',
                    ),
                    TaskListItem(
                      icon: Icons.description,
                      label: 'Detail:',
                      value: taskData?['item_name'] ?? 'N/A',
                    ),
                    TaskListItem(
                      icon: Icons.assignment,
                      label: 'Task:',
                      value: '${taskData?['task_number']??'N/A'}/${taskData?['total_tasks']??'N/A'}',
                    ),
                    TaskListItem(
                      icon: Icons.inventory_2,
                      label: 'Item Number:',
                      value: taskData?['item_number'] ?? 'N/A',
                      valueColor: Colors.red
                    ),
                    // Item Number输入框（样式不变）
                    _buildKeyboardInput(
                      fieldType: 'item',
                      controller: _itemNumberController,
                      focusNode: _itemNumberFocusNode,
                      onSubmitted: _handleItemNumberScanInput,
                      isSmallScreen: isSmallScreen,
                    ),
                    TaskListItem(
                      icon: Icons.location_on,
                      label: 'Location:',
                      value: taskData?['location'] ?? 'N/A',
                      valueColor: Colors.red
                    ),
                    // Location输入框（样式不变）
                    _buildKeyboardInput(
                      fieldType: 'location',
                      controller: _locationController,
                      focusNode: _locationFocusNode,
                      onSubmitted: (_) => _focusOnField('lpn', showKeyboard: false),
                      isSmallScreen: isSmallScreen,
                    ),
                    TaskListItem(
                      icon: Icons.confirmation_number,
                      label: 'LPN/BIN:',
                      value: taskData?['lpn'] ?? 'N/A',
                      valueColor: Colors.red
                    ),
                    // LPN/BIN输入框（样式不变）
                    _buildKeyboardInput(
                      fieldType: 'lpn',
                      controller: _lPNBINController,
                      focusNode: _lPNFocusNode,
                      onSubmitted: (_) => _focusOnField('quantity', showKeyboard: true),
                      isSmallScreen: isSmallScreen,
                    ),
                    TaskListItem(
                      icon: Icons.scale,
                      label: 'Quantity:',
                      value: '${taskData?['required_quantity']??'0'} (${taskData?['pack_type']??'N/A'})',
                      valueColor: Colors.red
                    ),
                    Row(
                      children: [
                        Expanded(
                          // Quantity输入框（样式不变）
                          child: _buildKeyboardInput(
                            fieldType: 'quantity',
                            controller: _qtyController,
                            focusNode: _quantityFocusNode,
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                              RangeInputFormatter(maxAllowedValue)
                            ],
                            onSubmitted: (_) => _resetAllKeyboards(),
                            isSmallScreen: isSmallScreen,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          taskData?['pack_type'] ?? 'N/A',
                          style: TextStyle(
                            fontSize: 13 * _fontScale,
                            color: Colors.black87
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8),
              child: Column(
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text('Next', style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14 * _fontScale,
                        color: Colors.white
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: loadNextTask,
                    ),
                  ),
                  const SizedBox(height: 3),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text('Picking Detail', style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14 * _fontScale,
                        color: Colors.white
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: () {
                        _resetAllKeyboards();
                        Navigator.pushNamed(
                          context,
                          '/picking/picking-details',
                          arguments: {
                            'waveId': waveId,
                            'source': sourceScreen
                          }
                        ).then((result) {
                          if (result == true) {
                            setState(() {
                              _itemNumberController.clear();
                              _locationController.clear();
                              _lPNBINController.clear();
                              _qtyController.clear();
                            });
                            _callGetPickTaskAPI();
                            if (mounted) _focusOnField('item', showKeyboard: false);
                          }
                        });
                      },
                    ),
                  ),
                  const SizedBox(height: 3),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text('Exception', style: TextStyle(
                        fontWeight: FontWeight.bold,
                        fontSize: 14 * _fontScale,
                        color: Colors.white
                      )),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: () {
                        _resetAllKeyboards();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}